<?php
/**
 * Created by PhpStorm.
 * User: zhixuedong
 * Date: 2022/8/22
 * Time: 19:23
 */

namespace app\project\controller;


use app\api\controller\Common;
use app\api\service\ProAccountService;
use app\project\service\AdvancePlanService;
use app\project\service\ProjectService;
use app\project\service\ProjectTypeService;
use app\project\service\PublicService;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;

class AdvancePlan extends Controller
{

    //获取推进计划列表
    public function index()
    {
        $status = [0=>"待审核",1=>"已通过",2=>"已驳回"];
        //查询项目信息
        $where['status']    = 1;
        $pro_id             = empty($_GET['id'])?0:$_GET['id'];
        $field = "id,pid,name,menuTop,sort";
        $order  = "sort asc,id desc";
        $common = new Common();
        $proDetail = Db::name("project_pro")->where("id",$pro_id)->field("id,library,plan_category,pid,title")->find();

        $library = empty($proDetail['library'])?0:$proDetail['library'];
        $type = 0;
        if($proDetail['plan_category'] == 1){
            $type = 20;
        }
        if($proDetail['plan_category'] == 2){
            $type = 21;
        }

        //获取推进计划
        if($library==1){
            $library = 2;
        }
        $parentWhere['library'] = ['like',"%".$library."%"];
        $parentWhere['pid'] = 0;
        $parentWhere['type'] = $type;
        $parentWhere['status'] = 1;
        $list = Db::name("project_type")->where($parentWhere)->order("sort asc,id desc")->select();
        $pro_id = empty($proDetail['pid'])?$proDetail['id']:$proDetail['pid'];

        if($list){
            //获取推进计划子级
            foreach ($list as $k=>$v){
                unset($childWhere);
                $childWhere['library'] = ['like',"%".$library."%"];
                $childWhere['pid'] = $v['id'];
                $childWhere['status'] = 1;
                $child = Db::name("project_type")->where($childWhere)->order("sort asc,id desc")->select();

                foreach ($child as $key=>$val){
                    //查询计划内容是否存在
                    $infoWhere['type_id'] = $val["id"];
                    $infoWhere['pro_id'] = $pro_id;
                    $info                       = $common->public_select("project_pro_advance_plan",$infoWhere,'id,time,color,status,content,duty_unit')->order("id desc")->find();
                    $child[$key]['time'] = empty($info['time'])?"-":$info['time']; //计划时间
                    $child[$key]['color'] = isset($info['color'])?$info['color']:"-"; //旗子颜色

                    $child[$key]['is_shen'] = 0;  //是否需要审核
                    if (!empty($info)){
                        if($info['content']!='' & $info['status']==0){
                            $child[$key]["is_shen"] = 1;
                        }
                    }
                    $child[$key]['plan_id'] = empty($info['id'])?"-":$info['id'];  //推进计划id

                    if($info['content']!=""){
                        $child[$key]["status"]  = empty($status[$info['status']])?"-":$status[$info['status']]; //审核状态
                    }else{
                        $child[$key]["status"]  = empty($status[$info['status']])?"-":"待汇报"; //审核状态
                    }
//                    if(!empty($info["status"])){
//                        $key["status"]                = empty($status[$info["status"]])?"-":$status[$info["status"]];
//                    }

                    $child[$key]['duty_unit'] = empty($info['duty_unit'])?"-":$info['duty_unit'];  //服务单位
                    //是否存在未审核的延期申请
                    unset($where);
                    $where['pro_id'] = $pro_id;
                    $where['type_id'] = $val['id'];
                    $where['status'] = 0;
                    $applyCount = PublicService::counService("project_pro_advance_apply",$where);
                    $child[$key]['applyCount'] = $applyCount; //申请延期数量

                }

                $list[$k]['child'] = $child;
            }
        }
        //计划类别
        $plan_category = \think\Config::get("plan_category");
        $assign['plan_category'] = $plan_category;
        $assign['pro_id'] = $pro_id;
        $assign['list'] = $list;
        $assign['detail'] = $proDetail;
        $this->assign($assign);
        return $this->fetch('index');
    }

    //推进计划详情
    public function detail(){
        $id = empty($_GET['id'])?0:$_GET['id'];
        $where['id'] = $id;
        if(!empty($classify_id)){
            $where['classify_id'] = $classify_id;
        }
        $detail = AdvancePlanService::detailService($where);

        if(!empty($detail["add_id"])){
            //查询提交人
            $accountWhere['id'] = $detail["add_id"];
            $Accoun = ProAccountService::detailService($accountWhere,1);
        }
        $detail['addName'] =  empty($Accoun)?"":$Accoun['name'];

        if(!empty($detail['images'])){
            $detail['images'] = explode(";",$detail['images']);
        }else{
            $detail['images'] = [];
        }

        $assign['type_id'] = empty($_GET['type_id'])?0:$_GET['type_id'];
        //判断是否是拷贝项目
        $copyWhere['id'] = empty($_GET['proId'])?0:$_GET['proId'];
        $pid = Db::name("project_pro")->where($copyWhere)->value("pid");
        $proId = empty($pid)?$_GET['proId']:$pid;
        $assign['proId'] = $proId;
        $assign['detail'] = $detail;
        $this->assign($assign);

        $Communal = new Communal();
        $duty_unit = $Communal->dictionary("project_dictionaries");
        $this->assign("duty_unit", json_encode($duty_unit));

        $duty_unit_v = explode(";", trim($detail['duty_unit'], ";"));
        $duty_unit_k = $this->takekey($duty_unit, $duty_unit_v);
        $this->assign('duty_unit_k', json_encode($duty_unit_k));


        return $this->fetch("detail");
    }

    //执行保存
    public function save(){
        try{
            $data = $_POST;

            //判断是否是拷贝项目
            $duty_unit = isset($data['duty_unit']) ? $data['duty_unit'] : '';
            $duty_unit = json_decode($duty_unit, true);
            $dutyIds = [];
            foreach ($duty_unit as $value) {
                $dutyIds[] = $value['title'];
            }
            $dutyIds = implode(';', $dutyIds);
            $data['duty_unit'] = $dutyIds;

            $copyWhere['id'] = $data['pro_id'];
            $detail = Db::name("project_pro")->where($copyWhere)->field("id,pid,plan_category")->find();
            $data['pro_id'] = empty($pid)?$data['pro_id']:$pid;


            if(empty($data['id'])){
                if(empty($data['time'])){
                    throw new Exception("计划时间不能为空");
                }
//                $data['status'] = 0;
//                $data['color'] = 0;
                $data['addtime']    = date("Y-m-d H:i:s");
            }

            $data['adopttime'] = date("Y-m-d H:i:s");
            $data['adopt_id'] = Session::get("id");
            //审核通过了就显示绿色，驳回以及其他情况显示灰色
            if(empty($data["status"])){
                $data["status"] = 0;
            }
            $nowTime = date("Y-m-d");
            $day = (strtotime($nowTime)-strtotime($data['time'])) / 86400;

            if($data["status"]==1){
                $data["color"] = 1;
//                $data["time"] = "已完成";
            }elseif ($data["status"]==2){
                $data["color"] = 0;
                if($day>=1){
                    $data["color"] = 2;
                }
                if($day>30){
                    $data["color"] = 3;
                }
            }else{
                $data["color"] = 0;
                if($day>=1){
                    $data["color"] = 2;
                }
                if($day>30){
                    $data["color"] = 3;
                }
            }
            AdvancePlanService::saveService($data);

            //拷贝操作
            if($data['type_id']==350 & $data["status"]==1 & $detail['plan_category']==2){
                $common = new Common();
                $where['id'] = $data['pro_id'];
                $copyDate = $common->public_select("project_pro",$where)->find();
                unset($copyWhere);
                $copyWhere['library'] = 5;
                $copyWhere['pid'] = empty($copyDate['pid'])?$copyDate['id']:$copyDate['pid'];
                $copyId = $common->public_select("project_pro",$copyWhere)->value('id');
                if(empty($copyId)){
                    //拷贝至入统库
                    $copyDate['library'] = 5;
                    $copyDate['warehousingTime'] = date("Y-m-d");
                    $copyDate['addtime'] = date("Y-m-d H:i:s");
                    $copyDate['add_id'] = Session::get("id");
                    $copyDate['pid'] = empty($copyDate['pid'])?$copyDate['id']:$copyDate['pid'];
                    unset($copyDate['id']);
                    $common->handle("project_pro",$copyDate,1);
                }
            }


            //转库操作
            /*if(!empty($data['id'])) {
                //查询项目信息
                $pro_id = empty($data['pro_id']) ? 0 : $data['pro_id'];
                $proDetail = Db::name("project_pro")->where("id", $pro_id)->find();
                $library = empty($proDetail["library"]) ? 0 : $proDetail["library"];
                $menuTop = empty($proDetail['menuTop'])?1:$proDetail['menuTop'];
                if ($library == 1) {
                    $type = 1;
                } elseif ($library == 3) {
                    $type = 2;
                    $typeWhere['menuTop'] = $menuTop;
                } else {
                    $type = 3;
                }
                $field = "id,pid,name,menuTop,sort";
                $order = "sort asc,id desc";
                $common = new Common();
                $typeWhere['status'] = 1;
                $typeWhere['type'] = $type;
                $infoWhere['pro_id'] = ['in', $pro_id];
                $listCount = $common->public_select("project_pro_advance_plan", $infoWhere, 'id,time,color,status,content')->count("*");
                $infoWhere['status'] = 1;
                $infoCount = $common->public_select("project_pro_advance_plan", $infoWhere, 'id,time,color,status,content')->count("*");
                if($listCount==$infoCount){
                    if($library==1){ //签约库转建设库
                        Db::name("project_pro")->where("id", $pro_id)->update(['library'=>3]);
                    }
                    if($library==3){ //签约库转建设库
                        Db::name("project_pro")->where("id", $pro_id)->update(['library'=>6]);
                    }
                }
            }*/

            if ($data['type_id'] == 343) {
                // 计划开工时间，更新项目的拟开工时间时间
                Db::name("project_pro")->where(['pid'=>$data['pro_id']])->update(['plan_onstream_time'=>$data['time']]);
                //实际开工时间
                Db::name("project_pro")->where(['pid'=>$data['pro_id']])->update(['onstream_time'=>$data['time']]);
            }

            if ($data['type_id'] == 350) {
                // 计划开工时间，更新项目的拟投产时间时间
                Db::name("project_pro")->where(
                    [
                        'pid'=>$data['pro_id'],
                    ]
                )->update(['planned_production_time'=>$data['time']]);
            }

            //更新入库状态
            if ($data['type_id'] == 344) {
                if($data['status'] == 1){
                    unset($where);
                    unset($update);
                    $where['pid'] = $data['pro_id'];
                    $update['code'] = empty($data['code'])?"":$data['code'];
                    $update['warehousingTime'] = date("Y-m-d");
                    $update['warehousing'] = 2;
                    Db::name("project_pro")->where($where)->update($update);
                }
            }


            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //执行删除
    public function del(){
        try {
            $id = $_POST['id'];
            $where['id'] = ['in',$id];
            AdvancePlanService::delService($where);
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;

    }

    //更新状态视图
    public function statusView(){
        $id = empty($_GET['id'])?0:$_GET['id'];
        $where['id'] = $id;
        $detail = AdvancePlanService::detailService($where);
        $assign['detail'] = $detail;
        $this->assign($assign);
        return $this->fetch("statusView");
    }

    //更新状态
    public function dostatus(){
        try{
            $id = empty($_POST['id'])?0:$_POST['id'];
            $data['id'] = $id;

            if(!isset($_POST['status'])){
                throw new Exception("请选择操作选项");
            }
            $data['color'] = $_POST['status'];

//            dump($data);die;
//            $where['']

            AdvancePlanService::saveService($data);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    public function takekey($data, $value)
    {
        $black = [];
        foreach ($data as $k => $v) {
            if (in_array($v['title'], $value)) {
                $black[] = $v['value'];
            }
        }
        return $black;
    }
}